<template>
	<view class="wrap">
		<view class="logo">{{ appName }}</view>
		<div v-if="loginType === 'currentPhone'">
      <!-- <u-tabs :list="list" :is-scroll="false" :current="current" @change="onClickItem"></u-tabs> -->
      <view v-if="current === 0">
        <view class="list">
          <view class="list-call">
            <view class="iconfont icon-avatar" style="font-size: 22px;color:#5473e8;"></view>
            <input class="u-input" type="text" v-model="userName" maxlength="32" :placeholder="$t('login.placeholderAccount')" />
          </view>
          <view class="list-call">
            <view class="iconfont icon-key" style="font-size: 22px;color:#5473e8;"></view>
            <input class="u-input" type="text" v-model="password" maxlength="32" :placeholder="$t('login.placeholderPassword')" :password="!showPassword" />
            <image class="u-icon-right" :src="'/static/assets/login/eye_' + (showPassword ? 'open' : 'close') + '.png'" @click="showPass()"></image>
          </view>
          <div style="padding:15rpx 0 0;">
            <view v-if="false" class="register">
              <navigator class="register-link" url="forget" open-type="navigate">{{$t('login.forget')}}</navigator>
              <!-- <navigator class="register-link" url="reg" open-type="navigate">{{$t('login.reg')}}</navigator> -->
            </view>
            <u-checkbox v-model="rememberPassword" active-color="#5473e8">{{$t('login.remberPassword')}}</u-checkbox>
          </div>
        </view>
        <view class="button"  @click="submit('1')"><text>登录</text></view>
        <view class="login-bottom-box">
          <u-divider> 更多登录方式 </u-divider>
          <div class="login-unline">
            <uni-icons type="navigate" size="24" color="#497bff"></uni-icons>
            <a @click="handleLoginUnline">离线登录</a>
          </div>
          <!-- <view class="oauth2">
            <u-icon class="u-icon" size="100" color="#36c956" name="weixin-circle-fill" @click="wxLogin"></u-icon>
            <u-icon class="u-icon" size="100" color="#23a0f0" name="qq-circle-fill" @click="qqLogin"></u-icon>
          </view>
          <view class="copyright">
            登录即代表您已阅读并同意<u-link href="#">用户协议</u-link> 与 <u-link href="#">隐私政策</u-link>
          </view> -->
        </view>
      </view>
      <view v-if="current === 1">
        <view class="list">
          <view class="list-call" >
            <view class="iconfont icon-shouji" style="font-size: 22px;color:#5473e8;"></view>
            <u-field
              v-model="phoneNo"
              label="+86"
              placeholder="请填写手机号"
              style="width: 100%;"
              :border-bottom="false"
            >
            </u-field>
          </view>
          <div style="padding:25rpx 0 0;">
            还没有账号？<navigator class="reg-link" url="reg" open-type="navigate">{{$t('login.reg')}}</navigator>
          </div>
        </view>
        <view class="button"  @click="nextStep()"><text>下一步</text></view>
        <view class="login-bottom-box">
          <u-divider> 更多登录方式 </u-divider>
<!--          <div class="login-unline">
            <uni-icons type="navigate" size="24" color="#497bff"></uni-icons>
            <a @click="handleLoginUnline">离线登录</a>
          </div> -->
          <view class="oauth2">
            <u-icon class="u-icon" size="100" color="#36c956" name="weixin-circle-fill" @click="wxLogin"></u-icon>
            <u-icon class="u-icon" size="100" color="#23a0f0" name="qq-circle-fill" @click="qqLogin"></u-icon>
          </view>
          <view class="copyright">
            登录即代表您已阅读并同意<u-link href="#">用户协议</u-link> 与 <u-link href="#">隐私政策</u-link>
          </view>
        </view>
      </view>
		</div>
		<div v-else>
      <view class="currentPhone-box">
        <view class="number-text">183****1005</view>
        <view class="other-text">认证服务由中国移动提供。</view>
        <u-button type="primary" @click="submit('3')">本机号码一键登录</u-button>
        <u-button @click="qiehuanLogin()">其他登录方式</u-button>
      </view>
      <view class="login-bottom-box">
        <view class="copyright">
          登录即代表您已阅读并同意<u-link href="#">用户协议</u-link> 与 <u-link href="#">隐私政策</u-link>
        </view>
      </view>
		</div>
	</view>
</template>

<script>
import { loger } from '@daelui/dogjs/dist/components.js'
import { encrypt, decrypt } from '@/components/libs/jsencrypt.js'
import { login, getInfo, syncUserInfo } from '@/api/system/user.js'

export default {
	data() {
		return {
			appName: '移动应用',
			phoneNo:'',
			userName: '',
			password: '',
			loginType: 'currentPhone',
			showPassword: false,
			rememberPassword: true,
			isValidCodeLogin: false,
			validCode: '',
			imgValidCodeSrc: null,
			list: [{name: '用户名'}, {name: '手机号'}],
			current: 0,
			activeColor: '#007aff',
		};
	},
  async onLoad () {
		await this.$onLaunched
    this.initView()
		const systemInfo = uni.getSystemInfoSync()
		this.appName = systemInfo.appName
  },
	methods: {
    initView () {
			// 记录配置信息
			let remember = this.$store.state.vuex_remember || {}
			if (typeof remember.rememberPassword === 'boolean') {
				this.rememberPassword = remember.rememberPassword ? true : false
			}
			// 记录登录信息
			let user = this.getCurrentUser()
			if (user) {
				this.userName = user.userName
				if (this.rememberPassword) {
					this.password = decrypt(user.password)
				}
			}
		},
		showPass() {
			this.showPassword = !this.showPassword;
		},
		qiehuanLogin(){
			this.loginType = 'other'
		},
		onClickItem(index) {
      this.current = index;
    },
		refreshImgValidCode(e) {
			if (this.vuex_token == '') {
				this.$u.api.user.index().then(res => {
					this.imgValidCodeSrc = this.vuex_config.baseUrl + '/validCode?__sid='
						+ res.sessionid + '&t=' + new Date().getTime();
				});
			} else {
				this.imgValidCodeSrc = this.vuex_config.baseUrl + '/validCode?__sid='
						+ this.vuex_token + '&t=' + new Date().getTime();
			}
			this.validCode = '';
		},
		nextStep(){
			//验证码登录下一步
			uni.showLoading({
        title: '正在获取验证码',
        mask: true
      })
			this.$u.api.sendCode({
				phoneNo: this.phoneNo,
				validCodeType:'2'
			})
			.then(res => {
				if (res.code == '200') {
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/sys/login/code?phoneNo='+this.phoneNo
						});
					}, 500);
				}else{
					this.$u.toast(res.msg);
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/sys/login/code?phoneNo='+this.phoneNo
						});
					}, 500);
				}
			});
		},
		// 在线登录
    submit(loginType) {
			if (this.userName.length == 0) {
				this.$u.toast('请输入账号')
				return
			}
			if (this.password.length == 0) {
				this.$u.toast('请输入密码')
				return
			}
			this.$store.dispatch('Login', {
				username: this.userName,
				password: this.password,
				// validCode: this.validCode,
				// loginType: loginType
			}).then(res => {
        res = res || {}
        if (!res.success) {
          this.$u.toast(res.respondMessage || '登录失败')
          loger.error(res)
          return false
        }
        this.$u.toast('登录成功')
				this.$u.vuex('vuex_token', this.$store.state.user.token)

        let defer = Promise.resolve(true)
        if (res.user && res.user.userName) {
          defer = Promise.resolve(res)
        } else {
          defer = this.$store.dispatch('GetInfo')
        }
        // 请求用户信息
        defer.then(res => {
          res = res || {}
          if (!res.success) {
            this.$u.toast(res.respondMessage || '用户信息获取失败')
            loger.error(res)
            return false
          }
          let user = res.data || {}
					user.userName = user.username
          this.$u.vuex('vuex_user', { userName: user.userName })
          // 记录登录信息
          let users = this.$store.state.vuex_users
          users = Array.isArray(users) ? users : []
          let info = { password: encrypt(this.password), ...user }
          let one = users.find(item => item.userName === user.userName)
          if (!one) {
            users.push(info)
          } else {
            Object.assign(one, info)
          }
          this.$u.vuex('vuex_users', users)
          this.$u.vuex('vuex_mode', 'online')
					// 同步用户相关
					syncUserInfo(user, users, this.$u, this)
          // 记录配置信息
          this.rememberConfig(user)
          // 初始化数据后跳转
          Promise.resolve(this.initAppData(user)).finally(() => {
						uni.reLaunch({
							url: '/pages/sys/workbench/index'
						})
          })
        }).catch((e) => {
          this.$u.toast('用户信息请求失败')
        })
        // if (res.isValidCodeLogin){
        // 	this.isValidCodeLogin = true;
        // 	this.refreshImgValidCode();
        // }
			}).catch((e) => {
				this.$u.toast('登录失败')
				loger.error(e)
			})
		},
		// 离线登录
		handleLoginUnline () {
			if (this.userName.length === 0) {
				this.$u.toast('请输入账号')
				return
			}
			if (this.password.length === 0) {
				this.$u.toast('请输入密码')
				return
			}
		  // 记录登录信息
		  let userName = this.userName
		  let password = this.password
		  let users = this.$store.state.vuex_users
		  users = Array.isArray(users) ? users : []
		  let user = users.find(item => {
		    return item.userName === userName && decrypt(item.password) === password
		  })
		  if (user) {
		    // 记录配置信息
		    this.$u.vuex('vuex_token', '')
		    this.$u.vuex('vuex_user', { userName: user.userName })
				this.$u.vuex('vuex_mode', 'offline')
				this.rememberConfig(user)
		    // 初始化数据后跳转
		    this.initAppData(user, false)
		    // 跳转至工作台
		    uni.reLaunch({
		      url: '/pages/sys/workbench/index?source=welcome'
		    })
		  } else {
		    this.$u.toast('无用户信息');
		  }
		},
		// 记录配置
		rememberConfig (user) {
			// 记录配置信息
			let remember = this.$store.state.vuex_remember
			remember = remember || {}
			remember.rememberPassword = this.rememberPassword
			// 记录用户登录次数
			let count = remember[user.userId]
			if (!count) {
				remember[user.userId] = 1
			} else {
				remember[user.userId] = count + 1
			}
			this.$u.vuex('vuex_remember', remember)
		},
    wxLogin(res) {
			this.$u.toast('微信登录');
		},
		qqLogin() {
			this.$u.toast('QQ 登录');
		},
    // 初始化应用数据
    initAppData() {

    }
	}
};
</script>
<style lang="scss">
@import 'index.scss';
.wrap {
  .u-input::-webkit-input-placeholder,
  .uni-input-placeholder {
    font-size: 12px;
  }
}
.logo {
	font-size: 46rpx;
	color: #5473e8;
	margin: 80rpx auto 80rpx auto;
}
.list-call-icon{
	color: #ff0000;
}
.currentPhone-box{
	text-align: center;
	padding: 40rpx 80rpx;
	.number-text{
		color: #000000;
		font-size: 60rpx;
	}
	.other-text{
		color: #999999;
		font-size: 26rpx;
		padding: 20rpx 0;
	}
	.u-btn{
		margin: 30rpx auto;
	}
	.u-hairline-border{
	    border: 1px solid #fff;
	}
}

.register {
	display:inline-block;
	color: #5473e8;
	height: 40rpx;
	line-height: 40rpx;
	font-size: 28rpx;
	float:right;
	margin-top: 6rpx;
}
.register-link{
	float: right;
	padding: 0 16rpx;
}
.reg-link{
	display: inline-block;
	color: #5473e8;
}
.oauth2 {
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	margin: 0rpx 100rpx 30rpx;

	image {
		height: 80rpx;
		width: 80rpx;
	}
}
.u-tabs{
	padding: 0 70rpx;
}
.login-unline {
  margin: 0 auto;
  width: 80%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  text-align: right;
  color: #497bff;
}
</style>
